package com.example.demo.controller;

import java.io.IOException;

import org.elasticsearch.action.admin.indices.delete.DeleteIndexRequest;
import org.elasticsearch.action.support.master.AcknowledgedResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.CreateIndexResponse;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;

import jakarta.annotation.Resource;

/**
 * 索引
 */
@RestController
@RequestMapping("/index")
public class IndexController {

    private final static String INDEX_NAME = "dog_index";
    @Resource
    private RestHighLevelClient restHighLevelClient;

    /**
     * 创建索引
     */
    @RequestMapping("/1")
    public String test1() throws IOException {

        // 1、创建索引请求
        CreateIndexRequest request = new CreateIndexRequest(INDEX_NAME);
        // 2、执行请求
        CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(request, RequestOptions.DEFAULT);
        System.out.println("createIndexResponse = " + createIndexResponse);

        return JSON.toJSONString(createIndexResponse);

    }

    /**
     * 判断索引是否存在
     */
    @RequestMapping("/2")
    public String test2() throws IOException {

        GetIndexRequest request = new GetIndexRequest(INDEX_NAME);
        boolean exists = restHighLevelClient.indices().exists(request, RequestOptions.DEFAULT);
        System.out.println("exists = " + exists);

        return JSON.toJSONString(exists);

    }

    /**
     * 删除索引
     */
    @RequestMapping("/3")
    public String test3() throws IOException {

        DeleteIndexRequest request = new DeleteIndexRequest(INDEX_NAME);
        AcknowledgedResponse delete = restHighLevelClient.indices().delete(request, RequestOptions.DEFAULT);
        System.out.println("delete = " + delete);

        return JSON.toJSONString(delete);

    }

}
